<?php

class IndexController extends Zend_Controller_Action {
	/*
	 * Контейнер для ACL
	 * @var Zend_Acl
	 */
	private $_acl = null;

	/*
	 * Контейнер для db
	 * @var Zend_Db
	 */
	private $_db = null;

	/*
	 * Контейнер для user
	 * @var Zend_Auth
	 */
	private $_user = null;
	
	public function init() {
		// Инит ACL
		$this->_acl = Zend_Registry::get('acl');
		// Инит DB
		$this->_db = Zend_Registry::get('db');
		// инит пользователя
		$this->_user = Zend_Auth::getInstance()->getIdentity();
	}

	/*
	 * Гостевая книга
	 */
	public function indexAction() {
		$gbConfig = new Zend_Config_Ini(APPLICATION_PATH . '/configs/gb.ini');
		$page = $this->_getParam('page');
		$perpage = $gbConfig->get('perpage');
		$gbModel = new Application_Model_Gb();

		// Настройка постраничного вывода
		$select = $this->_db->select()->from('gb');
		$zpAadapter = new Zend_Paginator_Adapter_DbSelect($select);
		$paginator = new Zend_Paginator($zpAadapter);
		$paginator->setCurrentPageNumber($page)
				->setItemCountPerPage($perpage);

		$user = new Application_Model_Users();
		$userId = $this->_user->id;
		$role = $user->getRole($userId);
		$this->_acl->isAllowed($role, 'gbPost') ? $guestbookForm = new Application_Form_Guestbook() : $guestbookForm = null;

		$this->view->assign('paginator', $paginator);
		$this->view->assign('gbList', $gbModel->getGbList($page, $perpage));
		$this->view->assign('guestbookForm', $guestbookForm);
	}

	/*
	 * Добавление сообщения в гостевую книгу
	 */
	public function addAction() {
		$user = new Application_Model_Users();
		$userId = $this->_user->id;
		$role = $user->getRole($userId);
		if ($this->_acl->isAllowed($role, 'gbPost')) {
			if ($this->getRequest()->isPost()) {
				$guestbookForm = new Application_Form_Guestbook();
				$data = $this->getRequest()->getParams();
				$data['user'] = $userId;
				if ($guestbookForm->isValid($data)) {
					$gbItem = new Application_Model_GbItem($data);
					$gbModel = new Application_Model_Gb();
					$gbModel->save($gbItem);
				}
			}
		}
		$this->_redirect('/');
	}

}

